﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace TjZheng.WebApi.Test.Models
{
    public static class SecurityHelper
    {
        /// <summary>
        /// 加密身份验证票据
        /// </summary>
        /// <typeparam name="T">要存储的用户对象的类型<peparam>
        /// <param name="data">要存储在Cookie里的对象</param>
        /// <param name="expiration">过期时间</param>
        /// <param name="isPersistent">如果票证将存储在持久性 Cookie 中（跨浏览器会话保存），则为 true；否则为 false。 如果该票证存储在 URL 中，将忽略此值。</param>
        /// <returns>身份验证票据</returns>
        public static string EncryptTicket<T>(T data, DateTime expiration, bool isPersistent = false)
        {
            try
            {
                string userData = JsonConvert.SerializeObject(data);
                //建立验证票据
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "tjzheng", DateTime.Now, expiration, isPersistent, userData);
                //加密票据
                return FormsAuthentication.Encrypt(ticket);
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 加密身份验证票据
        /// </summary>
        /// <param name="userData">要存储在票据里的数据</param>
        /// <param name="expiration">过期时间</param>
        /// <param name="isPersistent">如果票证将存储在持久性 Cookie 中（跨浏览器会话保存），则为 true；否则为 false。 如果该票证存储在 URL 中，将忽略此值。</param>
        /// <returns>身份验证票据</returns>
        public static string EncryptTicket(string userData, DateTime expiration, bool isPersistent = false)
        {
            try
            {
                //建立验证票据
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "tjzheng", DateTime.Now, expiration, isPersistent, userData);
                //加密票据
                return FormsAuthentication.Encrypt(ticket);
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 解密身份验证票据
        /// </summary>
        /// <param name="encryptedTicket">加密的验证票据</param>
        /// <returns></returns>
        public static FormsAuthenticationTicket DecryptTicket(string encryptedTicket)
        {
            try
            {
                return FormsAuthentication.Decrypt(encryptedTicket);
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}